import { defineStore } from 'pinia'
import { RouteRecordRaw, RouteLocationNormalized, RouteRecordNormalized } from 'vue-router'
import router from '@/router/index'

export default defineStore({
  id: 'layout',
  state: () => {
    return {
      isCollapse: false,
      menuList: [] as IMenuItem[],
      userRouters: [] as ITreeMenuItem[],
      navList: [] as RouteLocationNormalized[]
    }
  },
  actions: {
    updateIsCollapse(val: boolean) {
      this.isCollapse = val
    },
    async getMenuList() {
      // this.menuList = (await flux.api.user.getUserMenu(flux.util.storage.get('uid'))) as IMenuItem[]
    },
    // 获取用户树形结构菜单
    async setUserRouters(uid: string) {
      // this.menuList = (await flux.api.user.getUserMenu(uid)) as IMenuItem[]
      console.log(this.menuList)
      this.userRouters = getTreeMenus(this.menuList)
    },
    //关闭nav导航
    closeNav(index: number) {
      console.log(index, 'index')
      this.navList.splice(index, 1)
    },
    //新增nav导航
    setNavList(route: RouteLocationNormalized) {
      if (this.navList.length == 20) this.navList.pop()
      const isExist = this.navList.find((h) => h.name == route.name)
      console.log(isExist, 'isExist')
      if (!isExist && !route.meta?.menu?.blank) this.navList.unshift(route)
    },
    //关闭当前标签和首页标签之外的所有标签
    cloneOtherNav(route: RouteRecordRaw) {
      this.navList = []
      // this.setNavList(currentPath)
    },
    resetNavList() {
      this.navList = []
    }
  }
})

interface ICache {
  [key: number]: ITreeMenuItem
}
/**
 * @description 转换树形结构菜单
 * @param menuList 菜单列表
 */
const getTreeMenus = (menuList: IMenuItem[]): ITreeMenuItem[] => {
  const treeMenuList = [] as ITreeMenuItem[]
  const cache: ICache = {}
  menuList.forEach((treeItem) => {
    treeItem.meta = {
      icon: treeItem.icon,
      title: treeItem.title
    }
    cache[treeItem.rid] = treeItem
  })

  menuList.forEach((treeItem) => {
    const parent = cache[treeItem.pid]
    if (parent) {
      if (!parent.children) {
        parent.children = [] as IMenuItem[]
      }
      parent.children.push(treeItem)
    } else {
      treeMenuList.push(treeItem)
    }
  })
  return treeMenuList
}
